//
//  HarvestDetailViewController.m
//  BabyAndBabyDriver
//
//  Created by 范琦 on 16/8/16.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "HarvestDetailViewController.h"
#import "HarvestShopCell.h"
#import "DetailCell.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

@interface HarvestDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    MBProgressHUD *hud;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listArr1;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) NSDictionary *mainDic;

@property (nonatomic, assign) CGFloat money;
@property (nonatomic, strong) NSDictionary *ceshiDic;

@end

@implementation HarvestDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订单详情";
    self.listArr1 = [NSMutableArray arrayWithObjects:@"商户名称:测试商户", @"地址:测试地址", @"电话:15840840610", @"收款方式:余额", nil];

    [self creatTableView];
    if ([_str isEqualToString:@"done"]) {
        
        [self creatOtherView];
    }else{
        [self creatOtherView1];
    }
    
    
    if ([_mainStr isEqualToString:@"未完成"]) {
        
    }
    
    [self netHandle];
    
}
- (void)netHandle
{
    self.arr = [NSMutableArray array];
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Mall/detail" paramDic:@{@"token":TOKEN, @"id":_myId} RegisterApiMethod:RequestMethodPost];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        self.mainDic = request.responseBody[@"result"];
        self.listArr1 = [NSMutableArray arrayWithObjects:
                         [NSString stringWithFormat:@"商户名称: %@",self.mainDic[@"name_merchant"]],
                         [NSString stringWithFormat:@"联系人: %@",self.mainDic[@"contact_name"]],
                         [NSString stringWithFormat:@"电话: %@",self.mainDic[@"contact_phone"]],
                         [NSString stringWithFormat:@"地址: %@",self.mainDic[@"address"]],
                         nil];
        
        for (NSDictionary *dic in self.mainDic[@"goods"]) {
            
            [self.arr addObject:dic];
            
        }
        _moneyLabel.text = [NSString stringWithFormat:@"实收款:%@", self.mainDic[@"price"]];

        [_tableView reloadData];
    } failure:nil];
}
- (void)creatOtherView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, KSCREENHEIGHT - 104, KSCREENWIDTH, 1)];
    view.backgroundColor = TEXTCOLOR;
    [self.view addSubview:view];
    
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(KSCREENWIDTH - 150, KSCREENHEIGHT - 104, 130, 40)];
    _moneyLabel.text = [NSString stringWithFormat:@"实收款:%@", self.mainDic[@"price"]];
    _moneyLabel.textColor = [UIColor redColor];
    _moneyLabel.textAlignment = NSTextAlignmentRight;
    _moneyLabel.font = [UIFont systemFontOfSize:13];
    
    [self.view addSubview:_moneyLabel];
}


- (void)creatOtherView1
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, KSCREENHEIGHT - 154, KSCREENWIDTH, 1)];
    view.backgroundColor = TEXTCOLOR;
    [self.view addSubview:view];
    
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(KSCREENWIDTH - 150, KSCREENHEIGHT - 154, 130, 40)];
    _moneyLabel.text = @"实收款: 545元";
    _moneyLabel.textColor = [UIColor redColor];
    _moneyLabel.textAlignment = NSTextAlignmentRight;
    _moneyLabel.font = [UIFont systemFontOfSize:13];
    
    [self.view addSubview:_moneyLabel];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(20, KSCREENHEIGHT - 114, KSCREENWIDTH - 40, 40);
    btn.backgroundColor = BACKGROUNDCOLOR;
    [btn setTitle:@"成功" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:btn];
    btn.tintColor = [UIColor whiteColor];
    btn.layer.cornerRadius = 5;
    
    if ([_str isEqualToString:@"添加"]) {
        
    }
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            NSString *str = [_mainDic JSONString];

            YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"Mall/ok" paramDic:@{@"token":TOKEN, @"id":_myId, @"data":str} RegisterApiMethod:RequestMethodPost];
            [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                
                NSLog(@"%@", request.responseBody);
                if ([request.responseBody[@"error"] integerValue] == 0) {
                    [self hud:request.responseBody[@"msg"]];
                    [self.navigationController popViewControllerAnimated:YES];
                }

            } failure:nil];
            
            NSLog(@"失败");
            
            
        }];
    
}

- (void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT - 104) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 50;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerNib:[UINib nibWithNibName:@"HarvestShopCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    [_tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:@"cell2"];

    [self.view addSubview:_tableView];
    
    _tableView.showsVerticalScrollIndicator = NO;
    
    
    
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return 0;
  
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arr.count + _listArr1.count;
}


// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 4) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.textColor = [UIColor colorWithRed:141/255.0 green:141/255.0 blue:141/255.0 alpha:1];
        cell.textLabel.text = _listArr1[indexPath.row];
        
        return cell;
    }else{
    
        if ([_mainStr isEqualToString:@"未完成"]) {
            
            DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_arr[indexPath.row - _listArr1.count]];
            

            cell.title.text = [NSString stringWithFormat:@"%@", dic[@"name"]];
            
            cell.text.text = [dic[@"qty"] stringValue];
            cell.money.text = dic[@"price"];
            
            [[[cell.addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id x) {
               
                NSInteger i = [cell.text.text integerValue] + 1;
                [dic setObject:[NSNumber numberWithInteger:i] forKey:@"qty"];
                [_arr replaceObjectAtIndex:indexPath.row - _listArr1.count withObject:dic];
                
                [_tableView reloadData];
                [self getMoney];
                
            }];
            
            
            [[[cell.reduceBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id x) {
                
                if ([cell.text.text integerValue] >0) {
                    
                    NSInteger i = [cell.text.text integerValue] - 1;
                    [dic setObject:[NSNumber numberWithInteger:i] forKey:@"qty"];
                    [_arr replaceObjectAtIndex:indexPath.row - _listArr1.count withObject:dic];
                    
                    [_tableView reloadData];
                    [self getMoney];
                }
                
            }];
            
            [[[cell.text rac_signalForControlEvents:UIControlEventEditingDidEnd] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id x) {
                
                NSInteger i = [cell.text.text integerValue];
                [dic setObject:[NSNumber numberWithInteger:i] forKey:@"qty"];
                [_arr replaceObjectAtIndex:indexPath.row - _listArr1.count withObject:dic];
                
                [_tableView reloadData];
                [self getMoney];

            }];
            
            return cell;
            
        }
        HarvestShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSDictionary *dic = _arr[indexPath.row - _listArr1.count];
        
        cell.title.text = [NSString stringWithFormat:@"%@", dic[@"name"]];
        
        cell.number.text = [dic[@"qty"] stringValue];
        return cell;
    
    }
  
}

- (void)getMoney
{
    _money = 0;
    for (NSDictionary *dic in _arr) {
        
        CGFloat f = [dic[@"price"] floatValue];
        
        CGFloat i = [dic[@"qty"] integerValue];
        
        CGFloat all = f * i;
        
        _money += all;
    }
    _moneyLabel.text = [NSString stringWithFormat:@"实收款: %.2lf",_money];


}
- (void)hud:(NSString *)str
{
    
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    hud = [[MBProgressHUD alloc] initWithWindow:window];
    hud.removeFromSuperViewOnHide = YES;
    
    [window addSubview:hud];
    hud.labelText = str;
    hud.labelColor = [UIColor colorWithHexString:@"#A1A1AC"];
    hud.labelFont = [UIFont systemFontOfSize:15];
    hud.mode = MBProgressHUDModeCustomView;
    hud.progress = 0;
    
    [hud show:YES];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(hiden) userInfo:nil repeats:NO];
}
- (void)hiden
{
    [hud hide:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
